package com.debao.system.service.impl;

import java.util.*;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.debao.common.constant.Constants;
import com.debao.common.constant.WechatConstants;
import com.debao.common.core.domain.entity.SysUser;
import com.debao.common.enums.GoodsOrderStatus;
import com.debao.common.model.TempData;
import com.debao.common.model.WechatTemplateVo;
import com.debao.common.utils.AliyunSmsUtil;
import com.debao.common.wechat.WechatUtils;
import com.debao.system.domain.*;
import com.debao.system.domain.dto.ClassBuySuccessMiniProgramTempDto;
import com.debao.system.mapper.CourseCardMapper;
import com.debao.system.service.*;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.debao.system.mapper.CourseCardOrderMapper;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 课程卡订单Service业务层处理
 *
 * @author DeBao
 * @date 2024-06-19
 */
@Service
@Slf4j
public class CourseCardOrderServiceImpl implements ICourseCardOrderService {
    @Autowired
    private CourseCardOrderMapper courseCardOrderMapper;

    @Autowired
    private CourseCardMapper courseCardMapper;
    @Autowired
    private ISysUserService userService;

    @Autowired
    private IConfigService configService;

    @Autowired
    private ICoachService coachService;

    @Autowired
    private ITimeUserCardService timeCardService;

    @Autowired
    private IUserCourseCardService courseCardService;

    @Autowired
    private ICourseTypeService courseTypeService;

    @Autowired
    private ILogInfoService logInfoService;

    /**
     * 通知服务
     */
    @Resource
    private NotifyServer notifyServer;


    /**
     * 查询课程卡订单
     *
     * @param id 课程卡订单主键
     * @return 课程卡订单
     */
    @Override
    public CourseCardOrder selectCourseCardOrderById(Long id) {
        return courseCardOrderMapper.selectCourseCardOrderById(id);
    }

    /**
     * 用户有没有报名这个课程
     *
     * @param userId
     * @param cardId
     * @return
     */
    @Override
    public Boolean selectCourseCardOrderByUserId(Long userId, Long cardId) {
        return courseCardOrderMapper.selectCourseCardOrderByUserId(userId, cardId);
    }

    /**
     * 查询课程数量
     *
     * @param id
     * @return
     */
    @Override
    public Integer selectCourseCount(Long id) {
        return courseCardOrderMapper.selectCourseCount(id);
    }

    /**
     * 处理支付成功回调
     *
     * @param orderNo
     * @param transactionId
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = Exception.class)
    public void paySucHandleOrder(String orderNo, String transactionId) {
        if (StringUtils.isBlank(orderNo)) {
            log.error("订单回调更新数据失败, orderNo为空");
            return;
        }
        String logHead = String.format("订单回调更新, orderNo = %s ", orderNo);
        //获取订单信息
        CourseCardOrder courseCardOrder = courseCardOrderMapper.selectCourseCardOrderByOrderNo(orderNo);
        if (Objects.isNull(courseCardOrder)) {
            // todo 自定义异常类
            log.error(logHead + "订单不存在");
            return;
        }
        if (!StringUtils.equalsIgnoreCase(courseCardOrder.getStatus(), String.valueOf(GoodsOrderStatus.None))) {
            log.error(logHead + "订单信息回调已更新 status = {}", courseCardOrder.getStatus());
            return;
        }
        // 更新订单状态 【支付成功】
        courseCardOrder.setTransactionId(transactionId);
        courseCardOrder.setPayAt(new Date());
        courseCardOrder.setPayMoney(courseCardOrder.getMoney());
        courseCardOrder.setStatus(String.valueOf(GoodsOrderStatus.Paid));
        //
        int row = courseCardOrderMapper.updateCourseCardOrder(courseCardOrder);
        if (row != 1) {
            log.error(logHead + "订单更新失败");
            return;
        }
        //todo 根据购买的开的类型分别插入两张表 次卡表和月卡表
        CourseCard courseCard = courseCardMapper.selectCourseCardById(courseCardOrder.getCourseCardId());
        CourseType courseType = courseTypeService.selectCourseTypeById(courseCard.getTypeId());
        if (Objects.isNull(courseType)) {
            log.error("课程类型不存在");
            return;
        }
        Coach coach = coachService.selectCoachById(courseCard.getCoachId());
        SysUser user = userService.selectUserById(courseCardOrder.getUserId());
        String coachPhone = userService.getPhoneByUserId(coach.getUserId());
        String openId = userService.getOpenIdByUserId(courseCardOrder.getUserId());
        // 教练公众号openid
        String coachOpenId = userService.getAccountOpenIdByUserId(coach.getUserId());
        if (Objects.isNull(coach)) {
            throw new RuntimeException("教练不存在");
        }
        if (courseType.getType().equals(Constants.TIME_CARD)) {
            //次卡
            timeCardService.insertTimeUserCard(new TimeUserCard()
                    .setUserId(courseCardOrder.getUserId())
                    .setCourseId(courseCard.getId())
                    .setCoachId(courseCard.getCoachId())
                    .setSurplus(courseCard.getDuration()));
            // todo 推送通知
            notifyServer.openTimeCardNotify(openId,coachOpenId,courseCardOrder.getOrderNo(),
                    courseCardOrder.getMoney()/100+"元",
                    user.getPhonenumber(),
                    coachPhone,user.getNickName(),
                    coach.getName(),
                    courseCard.getName(),
                    DateUtil.format(courseCardOrder.getPayAt(), "yyyy-MM-dd HH:mm"));
        } else {
            // 天卡
            UserCourseCard dayCard = courseCardService.selectUserCourseCardByIdAndCourseId(courseCardOrder.getUserId(), courseCard.getId());
            if (Objects.isNull(dayCard)) {
                courseCardService.insertUserCourseCard(new UserCourseCard()
                        .setCourseCardId(courseCard.getId())
                        .setCoachId(courseCard.getCoachId())
                        .setUserId(courseCardOrder.getUserId())
                        .setStartAt(DateUtil.format(new Date(), "yyyy-MM-dd"))
                        .setEndAt(DateUtil.format(DateUtil.offsetDay(new Date(), courseCard.getDuration()), "yyyy-MM-dd")));
                notifyServer.openTimeCardNotify(openId,coachOpenId,courseCardOrder.getOrderNo(),
                        courseCardOrder.getMoney()/100+"元",
                        user.getPhonenumber(),
                        coachPhone,user.getNickName(),
                        coach.getName(),
                        courseCard.getName(),
                        DateUtil.format(courseCardOrder.getPayAt(), "yyyy-MM-dd HH:mm"));
            } else {
                // 卡失效时间
                String endAt = dayCard.getEndAt();
                // 比较当前时间和卡失效时间
                if (DateUtil.parse(endAt).before(new Date())) {
                    // 更新开始时间和结束时间
                    dayCard.setStartAt(DateUtil.format(new Date(), "yyyy-MM-dd"));
                    dayCard.setEndAt(DateUtil.format(DateUtil.offsetDay(new Date(), courseCard.getDuration()), "yyyy-MM-dd"));
                } else {
                    //续费
                    dayCard.setEndAt(DateUtil.format(DateUtil.offsetDay(DateUtil.parse(endAt), courseCard.getDuration()), "yyyy-MM-dd"));
                }
                // 更新卡信息
                courseCardService.updateUserCourseCard(dayCard);
                //todo 异步通知续卡成功
            }


        }
    }

    /**
     * 查询课程卡订单列表
     *
     * @param courseCardOrder 课程卡订单
     * @return 课程卡订单
     */
    @Override
    public List<CourseCardOrder> selectCourseCardOrderList(CourseCardOrder courseCardOrder) {
        return courseCardOrderMapper.selectCourseCardOrderList(courseCardOrder);
    }

    /**
     * 新增课程卡订单
     *
     * @param courseCardOrder 课程卡订单
     * @return 结果
     */
    @Override
    public int insertCourseCardOrder(CourseCardOrder courseCardOrder) {
        return courseCardOrderMapper.insertCourseCardOrder(courseCardOrder);
    }

    /**
     * 修改课程卡订单
     *
     * @param courseCardOrder 课程卡订单
     * @return 结果
     */
    @Override
    public int updateCourseCardOrder(CourseCardOrder courseCardOrder) {
        return courseCardOrderMapper.updateCourseCardOrder(courseCardOrder);
    }

    /**
     * 批量删除课程卡订单
     *
     * @param ids 需要删除的课程卡订单主键
     * @return 结果
     */
    @Override
    public int deleteCourseCardOrderByIds(Long[] ids) {
        return courseCardOrderMapper.deleteCourseCardOrderByIds(ids);
    }

    /**
     * 删除课程卡订单信息
     *
     * @param id 课程卡订单主键
     * @return 结果
     */
    @Override
    public int deleteCourseCardOrderById(Long id) {
        return courseCardOrderMapper.deleteCourseCardOrderById(id);
    }

    /**
     * 订单是否支付成功
     *
     * @param orderNo
     * @return
     */
    @Override
    public Boolean isPaySuccess(String orderNo) {
        return courseCardOrderMapper.isPaySuccess(orderNo);
    }

    @Override
    public CourseCardOrder selectCourseCardOrderByOrderNo(String orderNo) {
        return courseCardOrderMapper.selectCourseCardOrderByOrderNo(orderNo);
    }
}
